package com.thj.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.commons.web.servlet.BaseServlet;
import com.commons.po.Customer;
import com.commons.po.RolePo;
import com.commons.po.UserPo;
import com.commons.utils.StringUtils;
import com.hjf.web.servlet.BottomServlet;
import com.thj.dao.MenuDao;
import com.thj.dao.RoleDao;
import com.thj.dao.StatusmsgDao;
import com.thj.dao.impl.MenuDaoImpl;
import com.thj.dao.impl.RoleDaoImpl;
import com.thj.dao.impl.StatusmsgDaoImpl;
import com.thj.po.MenuPo;
import com.thj.po.StatusmsgPo;
import com.thj.service.RoleService;
import com.thj.service.impl.RoleServiceImpl;

public class RoleServlet extends BaseServlet {
	RoleService roleService=new RoleServiceImpl();
	private String encoding = "utf-8";
	public static int num=0;
	private List<Customer> list=new ArrayList<Customer>();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String opr=req.getParameter("opr");
		System.out.println("opr: "+opr);
		System.out.println(encoding);
		req.setCharacterEncoding(encoding);
		resp.setCharacterEncoding(encoding);
		resp.setContentType("text/html; charset=utf-8");
		
		
		if("add".equals(opr)){
			System.out.println("add roleservlet is working");
			System.out.println(req.getParameter("roleName"));
			add(req,resp);

		}else if("update".equals(opr)) {
			System.out.println("update roleservlet is working");
			update(req, resp);
		}else if("delete".equals(opr)) {
			System.out.println("操作");
			delete(req, resp);
		}else if("ban".equals(opr)){
			System.out.println("ban the roleid: " + req.getParameter("roleId"));
			
			ban(req, resp);
			
		}else if("active".equals(opr)){
			System.out.println("active the roleid: " + req.getParameter("roleId"));
			active(req, resp);
		}else if("menu".equals(opr)){
			setMenu(req, resp);
		}else if("savePrivilege".equals(opr)){//配置角色与菜单
			savePrivilege(req, resp);
		}else if("login".equals(opr)){
			index(req, resp);
		}else{
			extracted(req, resp);
			//req.getRequestDispatcher("/jsp/sys/thj/user/login.jsp").forward(req, resp);
		}
		/*
else if("list".equals(opr)){
			
			
		}*/
		
		
	}

	private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("indexServlet is working...");
		PrintWriter out=resp.getWriter();
		try{
			RoleDao roleDao = new RoleDaoImpl();
			int statusmsgId = StringUtils.str2Integer(req.getParameter("loginName"), false);
			System.out.println(req.getParameter("password"));
			System.out.println(req.getParameter("loginName"));
			
			StatusmsgDao statusmsgDao = new StatusmsgDaoImpl();
			StatusmsgPo statusmsgPo = statusmsgDao.findStaById(statusmsgId);
			//req.setAttribute("user", statusmsgPo);
			HttpSession session = req.getSession();
			session.setAttribute("zhi", "pass");
			//System.out.println(session.getAttribute("zhi"));
			String sessionId=session.getId();

			if(statusmsgPo.getCustomerPassword().equals(req.getParameter("password"))){
				statusmsgPo.getCustomerId();
				//statusmsgPo.getCustomerId()
				session.setAttribute("userInfo", statusmsgPo);
				//session.setAttribute("userPass", statusmsgPo.getCustomerPassword() + "");
				if(session.getId()!=null){
					System.out.println("或得到的session 为: " + session.getAttribute("userInfo"));
					//System.out.println("获得sessionpass为: " + session.getAttribute("userPass"));
				}else{
					System.out.println("session未获得: " + session.getId());
					
				}
				
				
				MenuDao menuDao = new MenuDaoImpl();
				System.out.println("RoleServlet113行没有问题");
				List<MenuPo>  menuList= menuDao.findByUId(statusmsgPo.getCustomerId());
				System.out.println("RoleServlet114行没有有问题");
				session.setAttribute("menuList", menuList);
				
				
				Customer currUser=this.getCurrUser(req.getSession());
				String opr=req.getParameter("loginName");
				if(currUser.getCustomer_id()!=(StringUtils.str2Integer(req.getParameter("loginName"), false)) ){
					list.add(currUser);
					num++;

				
				System.out.println("进入serverlet");
				System.out.println(num);
				req.setAttribute("onlineNum", num);
				
				
				
				req.getRequestDispatcher("/jsp/sys/thj/menu/index.jsp").forward(req, resp);
				
//				req.getRequestDispatcher("/jsp/sys/thj/menu/left.jsp").forward(req, resp);
//				req.setAttribute("test", "test");
//				req.getRequestDispatcher("/jsp/sys/thj/menu/left.jsp").forward(req, resp);
			}else{
				out.println("<script type='text/javascript'>alert('"+"登陆失败"+"');history.back();</script>");
			}
			}}catch(Exception e){
			out.println("<script type='text/javascript'>alert('"+"登陆失败"+"');history.back();</script>");
			
		}
		
		
		
		
	}

	private void savePrivilege(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		int rows=0;
		String msg="";
		Integer roleId=null;
		try {
			List<Integer> menuIdList=new ArrayList<Integer>();//menuId的集合列表
			//1、获得选中的菜单列表
			String[] menuIds=req.getParameterValues("resourceIdList");
			if(menuIds!=null && menuIds.length>0){
				for(String str:menuIds){
					Integer menuId=StringUtils.str2Integer(str, false);
					if(menuId!=null){
						menuIdList.add(menuId);
					}
				}
			}
			System.out.println("get RoleServlet's req.getParameter('roleId')");
			System.out.println("RoleServlet's req.getParameter('roleId'): "+req.getParameter("roleId"));
			//2、获得roleId
			roleId=StringUtils.str2Integer(req.getParameter("roleId"), false);
			//2、调用dao保存角色与菜单的配置关联
			rows=roleService.saveRoleMenu(roleId, menuIdList);
		} catch (Exception e) {
			e.printStackTrace();
			msg="保存失败:"+e.getMessage();
		}
		PrintWriter out=resp.getWriter();
		if(rows>0){
			out.println("<script type='text/javascript'>alert('保存成功');location.href='roleServlet?opr=loadPrivilege&roleId="+roleId+"';</script>");
		}else{
			out.println("<script type='text/javascript'>alert('"+msg+"');history.back();</script>");
		}
	}

	private void setMenu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("setMenu is working...");
		RoleDao roleDao = new RoleDaoImpl();
		
		RolePo role = roleDao.findbyId(StringUtils.str2Integer(req.getParameter("roleId"), false));
		System.out.println("role.getId: "+role.getRoleId());
		req.setAttribute("role", role);
		MenuDao menuDao = new MenuDaoImpl();
		List<MenuPo> list = menuDao.findByCondition(null);
		req.setAttribute("mainMenuList", list);
		
		System.out.println("req.getParameter's value is :");
		System.out.println("req.getParameter is not null");
		req.getRequestDispatcher("role_setPrivilegeUI.jsp").forward(req, resp);
		
		
	}

	private void active(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		RoleDao roleDao = new RoleDaoImpl();
		int rows = roleDao.activeRole(StringUtils.str2Integer(req.getParameter("roleId"), false));
		PrintWriter out=resp.getWriter();
		if(rows > 0){
			out.println("<script type='text/javascript'>alert('成功');location.href='roleServlet';</script>");
		}else{
			out.println("<script type='text/javascript'>alert('失败');location.href='roleServlet';</script>");
		}
	}

	private void ban(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		RoleDao roleDao = new RoleDaoImpl();
		int rows = roleDao.banRole(StringUtils.str2Integer(req.getParameter("roleId"), false));
		PrintWriter out=resp.getWriter();
		if(rows > 0){
			out.println("<script type='text/javascript'>alert('成功');location.href='roleServlet';</script>");
		}else{
			out.println("<script type='text/javascript'>alert('成功');location.href='roleServlet';</script>");
		}
	}

	private void add(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		/*
		 * 
		 * 
		 * 			
			java.sql.Timestamp roleTime=new java.sql.Timestamp(System.currentTimeMillis());//��õ�ǰϵͳʱ��
			
			RolePo rolePo = new RolePo();
			rolePo.setRoleName(req.getParameter("roleName"));
			rolePo.setRoleIntroduce(req.getParameter("roleIntroduce"));
			rolePo.setCreatedId(StringUtils.str2Integer(req.getParameter("createdId"), false));
//			rolePo.setCreatedDate(StringUtils.str2DateBySql(req.getParameter("createdDate"), false,"yyyy-MM-dd"));
			rolePo.setCreatedDate(roleTime);
		 * */
		int rows=0;
		String msg = "";
		Customer userPo=this.getCurrUser(req.getSession());
		try{
			java.sql.Timestamp roleTime=new java.sql.Timestamp(System.currentTimeMillis());
			RolePo rolePo = new RolePo();
			rolePo.setRoleName(req.getParameter("roleName"));
			System.out.println("req��ȡ����roleName: "+req.getParameter("roleName"));
			rolePo.setRoleIntroduce(req.getParameter("roleIntroduce"));
			System.out.println("req��ȡ����roleParameter: "+req.getParameter("roleIntroduce"));
			rolePo.setCreatedId(userPo.getCustomer_id());
//			rolePo.setCreatedDate(StringUtils.str2DateBySql(req.getParameter("createdDate"), false,"yyyy-MM-dd"));
			rolePo.setCreatedDate(roleTime);
			rolePo.setUpdatedId(userPo.getCustomer_id());
			rolePo.setUpdatedDate(roleTime);
			
			//3��������Ч��
			/* if(entity.getEmpno()==null){
				throw new RuntimeException("Ա����Ų���Ϊ��");
			} */
			if(StringUtils.strIsNull(rolePo.getRoleName())){
				throw new RuntimeException("Ա����������Ϊ��" + rolePo.getRoleName());
			}
			
			//4���������ݣ����õײ�daoʵ��
			System.out.println("roleaddservlet is add the data.");
			RoleDao empDao=new RoleDaoImpl();
			rows=empDao.saveRole(rolePo);
			

		}catch(Exception e){
			e.printStackTrace();
			msg="����ʧ�ܣ�"+e.getMessage()+"catch";
		}
		
		PrintWriter out=resp.getWriter();
		if(rows>0){
			out.println("<script type='text/javascript'>alert('����ɹ�');location.href='roleServlet';</script>");
		}else{
			out.println("<script type='text/javascript'>alert('"+msg+"');history.back();</script>");
		}
	}

	
	
	private void update(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		/*
		 * 
		 * 
		 * 			
			java.sql.Timestamp roleTime=new java.sql.Timestamp(System.currentTimeMillis());//��õ�ǰϵͳʱ��
			
			RolePo rolePo = new RolePo();
			rolePo.setRoleName(req.getParameter("roleName"));
			rolePo.setRoleIntroduce(req.getParameter("roleIntroduce"));
			rolePo.setCreatedId(StringUtils.str2Integer(req.getParameter("createdId"), false));
//			rolePo.setCreatedDate(StringUtils.str2DateBySql(req.getParameter("createdDate"), false,"yyyy-MM-dd"));
			rolePo.setCreatedDate(roleTime);
		 * */
			int roleId = StringUtils.str2Integer(req.getParameter("roleId"), false);
			System.out.println("update roleID is :" + req.getParameter("roleId"));
			RoleDao roleDao = new RoleDaoImpl();
			RolePo rolePo = roleDao.findbyId(roleId);
			req.setAttribute("rolePo", rolePo);
			if(req.getParameter("rolePo")==null){
				System.out.println("rolePo ��Ϊ��");
				try {
					req.getRequestDispatcher("role_update.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		/*String msg = "";
		UserPo userPo=this.getCurrUser(req.getSession());
		try{
			//2���������
			java.sql.Timestamp roleTime=new java.sql.Timestamp(System.currentTimeMillis());
			RolePo rolePo = new RolePo();
			rolePo.setRoleName(req.getParameter("roleName"));
			System.out.println("req��ȡ����roleName: "+req.getParameter("roleName"));
			rolePo.setRoleIntroduce(req.getParameter("roleIntroduce"));
			System.out.println("req��ȡ����roleParameter: "+req.getParameter("roleIntroduce"));
			rolePo.setCreatedId(userPo.getId());
//			rolePo.setCreatedDate(StringUtils.str2DateBySql(req.getParameter("createdDate"), false,"yyyy-MM-dd"));
			rolePo.setCreatedDate(roleTime);
			rolePo.setUpdatedId(userPo.getId());
			rolePo.setUpdatedDate(roleTime);
			
			//3��������Ч��
			 if(entity.getEmpno()==null){
				throw new RuntimeException("Ա����Ų���Ϊ��");
			} 
			if(StringUtils.strIsNull(rolePo.getRoleName())){
				throw new RuntimeException("Ա����������Ϊ��" + rolePo.getRoleName());
			}
			
			//4���������ݣ����õײ�daoʵ��
			System.out.println("roleaddservlet is add the data.");
			RoleDao empDao=new RoleDaoImpl();
			rows=empDao.saveRole(rolePo);
			

		}catch(Exception e){
			e.printStackTrace();
			msg="����ʧ�ܣ�"+e.getMessage()+"catch";
		}
		
		PrintWriter out=resp.getWriter();
		if(rows>0){
			out.println("<script type='text/javascript'>alert('����ɹ�');location.href='roleServlet';</script>");
		}else{
			out.println("<script type='text/javascript'>alert('"+msg+"');history.back();</script>");
		}
	}
	*/
	
	private void extracted(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<RolePo> list=roleService.findByCondition(null);
		req.setAttribute("list", list);
		req.getRequestDispatcher("role_list.jsp").forward(req, resp);
	}
	
	
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		int id = StringUtils.str2Integer(req.getParameter("roleId"), false);
		RoleDao roleDao = new RoleDaoImpl();
		int rows = roleDao.deleteRole(id);
		PrintWriter out=resp.getWriter();
		if(rows > 0){
			out.println("<script type='text/javascript'>alert('ɾ���ɹ�');location.href='roleServlet';</script>");
			//req.getRequestDispatcher("roleServlet?opr=list").forward(req, resp);
		}else{
			System.out.println("ɾ��ʧ��");
		}
	}
}
